
**********CRSP DAILY DATA*********
use PERMNO date RET PRC DLRET DLSTCD CFACPR using "$jfqa_rep/crsp_daily_all.dta", clear

rename PERMNO permno
rename RET ret
rename PRC prc 
rename DLRET dlret
rename DLSTCD dlstcd 
rename CFACPR cfacpr

qui{
*delete duplicates and clean prc
drop if date==date[_n-1] & permno==permno[_n-1]
replace prc=abs(prc)

*define dates
gen month=month(date)
gen year=year(date)

*de-listed returns
replace ret=dlret if missing(ret)
replace ret=-0.3 if missing(ret) & dlstcd==500
replace ret=-0.3 if missing(ret) & dlstcd==520
replace ret=-0.3 if missing(ret) & dlstcd>550 & dlstcd<575
replace ret=-0.3 if missing(ret) & dlstcd==580
replace ret=-0.3 if missing(ret) & dlstcd==584
replace ret=-1 if missing(ret) & ~missing(dlstcd)
drop dlstcd dlret

drop if missing(prc) & missing(ret)
}

*define adjusted prices for splits
qui{
gen monthyear=ym(year, month)
gen prc_div=prc if permno~=permno[_n-1] | month~=month[_n-1]
replace prc_div=prc_div[_n-1]*(1+ret) if missing(prc_div)

gen prc_split=prc/cfacpr
drop cfacpr
}

*keep only last ten days of month
qui{
gsort permno monthyear date
by permno monthyear: gen obs=_n
egen max_obs=max(obs), by(permno monthyear)
gen obs_dif=max_obs-obs
drop if obs_dif>9
drop obs max_obs obs_dif
}

*assign first and last observation of month
qui{
gen prc_div_first=prc_div if month~=month[_n-1] | permno~=permno[_n-1]
egen min_prc=sum(prc_div_first), by(permno monthyear)
replace min_prc=. if min_prc==0
replace prc_div_first=min_prc if missing(prc_div_first)
drop min_prc

gen prc_split_first=prc_split if month~=month[_n-1] | permno~=permno[_n-1]
egen min_prc=sum(prc_split_first), by(permno monthyear)
replace min_prc=. if min_prc==0
replace prc_split_first=min_prc if missing(prc_split_first)
drop min_prc

gen prc_div_last=prc_div if month~=month[_n+1] | permno~=permno[_n+1]
egen min_prc=sum(prc_div_last), by(permno monthyear)
replace min_prc=. if min_prc==0
replace prc_div_last=min_prc if missing(prc_div_last)
drop min_prc

gen prc_split_last=prc_split if month~=month[_n+1] | permno~=permno[_n+1]
egen min_prc=sum(prc_split_last), by(permno monthyear)
replace min_prc=. if min_prc==0
replace prc_split_last=min_prc if missing(prc_split_last)
drop min_prc
}

*calculate within month convexity measures
qui{
egen avgprc=mean(prc_div), by(permno monthyear)
gen ten_day_convex_div=((prc_div_first+prc_div_last)/2-avgprc)/((prc_div_first+prc_div_last)/2)
drop avgprc prc_div_first prc_div_last

egen avgprc=mean(prc_split), by(permno monthyear)
gen ten_day_convex_split=((prc_split_first+prc_split_last)/2-avgprc)/((prc_split_first+prc_split_last)/2)
drop avgprc prc_split_first prc_split_last
}

keep if permno~=permno[_n+1] | month~=month[_n+1] /*keep month end observation*/

keep permno month year ten_day_convex_div ten_day_convex_split

sort permno year month
drop if permno==permno[_n-1] & year==year[_n-1] & month==month[_n-1]

save "$jfqa_rep/17_Ten_Day_Convex.dta", replace

